﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace Canyala.Lagoon.Extensions
{
    public static class UIElementExtensions
    {
        public static UIElement FindParent<T>(this UIElement element)
        {
            do
            {
                element = VisualTreeHelper.GetParent(element) as UIElement;
                if (element == null)
                    return null; // We only allow UIElements...

                if (element.GetType().IsAssignableFrom(typeof(T)))
                    return element;
            }
            while (element != null);

            return null;
        }

        public static UIElement FindChild<T>(this UIElement element)
        {
            if (element.GetType().IsAssignableFrom(typeof(T)))
                return element;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                var child = VisualTreeHelper.GetChild(element, i) as UIElement;
                if (child == null)
                    return null; // We only allow UIElements...

                var subChild = child.FindChild<T>();
                if (subChild != null)
                    return subChild;                
            }

            return null;
        }

        public static void SendToBack(this UIElement element)
        {
            Canvas.SetZIndex(element, 0);
        }

        public static void BringToFront(this UIElement element)
        {
            Canvas.SetZIndex(element, 9999);
        }

    }
}
